//package com.wondream.myframework.app.request.profitsharing;
//
//import cn.hutool.core.io.FileUtil;
//import cn.hutool.core.io.file.FileWriter;
//import cn.hutool.json.JSONArray;
//import cn.hutool.json.JSONObject;
//import cn.hutool.json.JSONUtil;
//import com.fasterxml.jackson.databind.ObjectMapper;
//import com.fasterxml.jackson.databind.node.ObjectNode;
//import com.hy.core.ioc.transaction.HyTransContext;
//import com.hy.core.ioc.transaction.HyTransUtils;
//import com.hy.core.message.HyDataEntry;
//import com.hy.core.oopay.wx.enums.RequestMethod;
//import com.hy.core.oopay.wx.enums.RequestProtocol;
//import com.hy.core.oopay.wx.enums.WxApiType;
//import com.hy.core.oopay.wx.kit.*;
//import com.hy.core.util.CastUtil;
//import com.hy.core.util.StringUtil;
//import com.hy.core.utils.json.HyJsonUtils;
//import com.tencent.weixin.common.DomainDetectionUtil;
//import com.wechat.pay.contrib.apache.httpclient.WechatPayHttpClientBuilder;
//import org.apache.http.client.HttpClient;
//import org.apache.http.client.methods.HttpGet;
//import org.apache.http.client.methods.HttpPost;
//import org.apache.http.client.utils.URIBuilder;
//import org.apache.http.entity.StringEntity;
//import org.apache.http.util.EntityUtils;
//import org.slf4j.Logger;
//
//import java.io.ByteArrayInputStream;
//import java.io.ByteArrayOutputStream;
//import java.nio.charset.StandardCharsets;
//import java.security.PrivateKey;
//import java.security.cert.X509Certificate;
//import java.util.ArrayList;
//import java.util.Iterator;
//import java.util.List;
//import java.util.Map;
//
//public class WXPayRequest {
//
//    public static Map<String, Object> sendToWxPayV3(HyTransContext transContext, RequestMethod method, String urlPrefix, String urlSuffix, String body, Map<String, String> params){
//        Logger logger = transContext.getLogger();
//        String resJson = null;
//        if (method == RequestMethod.GET) {
//            resJson = HttpRequestUtil.getReq(urlPrefix, urlSuffix, params, null, logger, true);
//        } else if (method == RequestMethod.POST) {
//            resJson = HttpRequestUtil.postReq(urlPrefix, urlSuffix, body, null, logger);
//        }
//        if(StringUtil.isEmpty(resJson)){
//            return null;
//        }
//        return HyJsonUtils.jsonString2Map(resJson);
//    }
//
//    public static Map<String, Object> sendToWxPayV3New(HyTransContext transContext, RequestMethod method, String urlPrefix, String urlSuffix, Map<String, String> postData, Map<String, String> params){
//        String bodyAsString = wxPayV3(transContext, method, urlPrefix, urlSuffix, postData, params, true);
//        if(bodyAsString==null){
//            return null;
//        }
//        return HyJsonUtils.jsonString2Map(bodyAsString);
//    }
//
//    public static String wxPayV3(HyTransContext transContext, RequestMethod method, String urlPrefix, String urlSuffix, Map<String, String> postData, Map<String, String> params, boolean needPlatformCert){
//        Logger logger = transContext.getLogger();
//        try {
//            PrivateKey privateKey = getPrivateKey(Configure.getKeyPathV3());
//            List<X509Certificate> certificates = new ArrayList<>();
//            if(needPlatformCert) {
//                X509Certificate platformCertificate = PemUtil.loadCertificate(Configure.getPlatformCertPathV3());
//                certificates.add(platformCertificate);
//            }
//            WechatPayHttpClientBuilder builder = WechatPayHttpClientBuilder.create()
//                    .withMerchant(Configure.mchID, Configure.getCertificateSerialNumberV3(), privateKey)
//                    .withWechatpay(certificates);
//            // ... 接下来，你仍然可以通过builder设置各种参数，来配置你的HttpClient
//
//            // 通过WechatPayHttpClientBuilder构造的HttpClient，会自动的处理签名和验签
//            HttpClient httpClient = builder.build();
//
//            // 后面跟使用Apache HttpClient一样
//            org.apache.http.HttpResponse response = null;
//            if (method == RequestMethod.GET) {
//                if (null != params && !params.keySet().isEmpty()) {
//                    urlSuffix = urlSuffix.concat("?").concat(PayKit.createLinkString(params, true));
//                }
//                String url = urlPrefix.concat(urlSuffix);
//                URIBuilder uriBuilder = new URIBuilder(url);
//                HttpGet httpGet = new HttpGet(uriBuilder.build());
//                httpGet.addHeader("Accept", "application/json");
//                response = httpClient.execute(httpGet);
//            } else if (method == RequestMethod.POST) {
//                String url = urlPrefix.concat(urlSuffix);
//                HttpPost httpPost = new HttpPost(url);
//                httpPost.addHeader("Accept", "application/json");
//                httpPost.addHeader("Content-type","application/json; charset=utf-8");
//
//                ByteArrayOutputStream bos = new ByteArrayOutputStream();
//                ObjectMapper objectMapper = new ObjectMapper();
//
//                ObjectNode rootNode = objectMapper.createObjectNode();
//                Iterator<Map.Entry<String, String>> iterator = postData.entrySet().iterator();
//                while(iterator.hasNext()){
//                    Map.Entry<String, String> entry = iterator.next();
//                    rootNode.put(entry.getKey(), entry.getValue());
//                }
//                objectMapper.writeValue(bos, rootNode);
//
//                httpPost.setEntity(new StringEntity(bos.toString("UTF-8"), "UTF-8"));
//                response = httpClient.execute(httpPost);
//            }
//            // 后面跟使用Apache HttpClient一样
//            String bodyAsString = EntityUtils.toString(response.getEntity());
//            return bodyAsString;
//        }
//        catch (Exception e) {
//            return null;
//        }
//    }
//
//    public static PrivateKey getPrivateKey(String keyPath) throws Exception {
//        String originalKey = FileUtil.readUtf8String(keyPath);
//        String privateKey = originalKey.replace("-----BEGIN PRIVATE KEY-----", "").replace("-----END PRIVATE KEY-----", "").replaceAll("\\s+", "");
//        return RsaKit.loadPrivateKey(privateKey);
//    }
//
//    /**
//     * 请求分账
//     *
//     * @return
//     * @throws Exception
//     */
//    public static boolean profitSharing(HyTransContext transContext, String body){
//        HyDataEntry dataEntry = transContext.getMess().getDataEntry();
//        Map<String, Object> dataMap = sendToWxPayV3(transContext, RequestMethod.POST, RequestProtocol.HTTPS + DomainDetectionUtil.getDomain(), WxApiType.BRAND_PROFIT_SHARING_ORDERS.toString(), body, null);
//        if(dataMap==null){
//            return false;
//        }
//
//        String outOrderNo = CastUtil.castString(dataMap.get("out_order_no"));
//        String transactionId = CastUtil.castString(dataMap.get("transaction_id"));
//        String orderId = CastUtil.castString(dataMap.get("order_id"));
//        // 商户分账单号
//        dataEntry.setChildValue("outOrderNo", outOrderNo);
//        // 微信订单号
//        dataEntry.setChildValue("transactionId", transactionId);
//        // 微信分账单号
//        dataEntry.setChildValue("orderId", orderId);
//        HyTransUtils.setTransBusSRspSuccessResult(transContext);
//        return true;
//    }
//
//    /**
//     * 查询分账结果
//     *
//     * @return
//     * @throws Exception
//     */
//    public static boolean profitSharingQuery(HyTransContext transContext, Map<String, String> params){
//        HyDataEntry dataEntry = transContext.getMess().getDataEntry();
//        Map<String, Object> dataMap = sendToWxPayV3(transContext, RequestMethod.GET, RequestProtocol.HTTPS + DomainDetectionUtil.getDomain(), WxApiType.BRAND_PROFIT_SHARING_ORDERS.toString(), null, params);
//        if(dataMap==null){
//            return false;
//        }
//
//        String outOrderNo = CastUtil.castString(dataMap.get("out_order_no"));
//        String status = CastUtil.castString(dataMap.get("status"));
//        String transactionId = CastUtil.castString(dataMap.get("transaction_id"));
//        String orderId = CastUtil.castString(dataMap.get("order_id"));
//        String receivers = CastUtil.castString(dataMap.get("receivers"));
//        String finishAmount = CastUtil.castString(dataMap.get("finishAmount"));
//        String finishDescription = CastUtil.castString(dataMap.get("finishDescription"));
//        // 微信订单号
//        dataEntry.setChildValue("transactionId", transactionId);
//        // 商户分账单号
//        dataEntry.setChildValue("outOrderNo", outOrderNo);
//        // 微信分账单号
//        dataEntry.setChildValue("orderId", orderId);
//        // 分账单状态
//        dataEntry.setChildValue("status", status);
//        // 分账接收方列表
//        dataEntry.setChildValue("receivers", receivers);
//
//        // 分账金额
//        dataEntry.setChildValue("finishAmount", finishAmount);
//        // 分账描述
//        dataEntry.setChildValue("finishDescription", finishDescription);
//
//        HyTransUtils.setTransBusSRspSuccessResult(transContext);
//        return true;
//    }
//
//    /**
//     * 添加分账接收方
//     *
//     * @return
//     * @throws Exception
//     */
//    public static boolean profitSharingAddReceiver(HyTransContext transContext, String body){
//        HyDataEntry dataEntry = transContext.getMess().getDataEntry();
//        Map<String, Object> dataMap = sendToWxPayV3(transContext, RequestMethod.POST, RequestProtocol.HTTPS + DomainDetectionUtil.getDomain(), WxApiType.BRAND_PROFIT_SHARING_RECEIVERS_ADD.toString(), body, null);
//        if(dataMap==null){
//            return false;
//        }
//        String type = CastUtil.castString(dataMap.get("type"));
//        String account = CastUtil.castString(dataMap.get("account"));
//        // 分账接收方类型
//        dataEntry.setChildValue("type", type);
//        // 分账接收方账号
//        dataEntry.setChildValue("account", account);
//        HyTransUtils.setTransBusSRspSuccessResult(transContext);
//        return true;
//    }
//
//    /**
//     * 删除分账接收方
//     *
//     * @return
//     * @throws Exception
//     */
//    public static boolean profitSharingRemoveReceiver(HyTransContext transContext, String body){
//        HyDataEntry dataEntry = transContext.getMess().getDataEntry();
//        Map<String, Object> dataMap = sendToWxPayV3(transContext, RequestMethod.POST, RequestProtocol.HTTPS + DomainDetectionUtil.getDomain(), WxApiType.BRAND_PROFIT_SHARING_RECEIVERS_delete.toString(), body, null);
//        if(dataMap==null){
//            return false;
//        }
//        String type = CastUtil.castString(dataMap.get("type"));
//        String account = CastUtil.castString(dataMap.get("account"));
//        // 分账接收方类型
//        dataEntry.setChildValue("type", type);
//        // 分账接收方账号
//        dataEntry.setChildValue("account", account);
//        HyTransUtils.setTransBusSRspSuccessResult(transContext);
//        return true;
//    }
//
//    /**
//     * 完结分账
//     *
//     * @return
//     * @throws Exception
//     */
//    public static boolean profitSharingFinish(HyTransContext transContext, String body){
//        HyDataEntry dataEntry = transContext.getMess().getDataEntry();
//        Map<String, Object> dataMap = sendToWxPayV3(transContext, RequestMethod.POST, RequestProtocol.HTTPS + DomainDetectionUtil.getDomain(), WxApiType.BRAND_PROFIT_SHARING_FINISH_ORDER.toString(), body, null);
//        if(dataMap==null){
//            return false;
//        }
//        String nonceStr = CastUtil.castString(dataMap.get("nonce_str"));
//        String outOrderNo = CastUtil.castString(dataMap.get("out_order_no"));
//        String transactionId = CastUtil.castString(dataMap.get("transaction_id"));
//        String orderId = CastUtil.castString(dataMap.get("order_id"));
//        // 随机字符串
//        dataEntry.setChildValue("nonceStr", nonceStr);
//        // 商户分账单号
//        dataEntry.setChildValue("outOrderNo", outOrderNo);
//        // 微信订单号
//        dataEntry.setChildValue("transactionId", transactionId);
//        // 微信分账单号
//        dataEntry.setChildValue("orderId", orderId);
//        HyTransUtils.setTransBusSRspSuccessResult(transContext);
//        return true;
//    }
//
//    /**
//     * 查询订单待分账金额
//     *
//     * @return
//     * @throws Exception
//     */
//    public static boolean profitSharingOrderAmountQuery(HyTransContext transContext, String transactionId){
//        HyDataEntry dataEntry = transContext.getMess().getDataEntry();
//        Map<String, Object> dataMap = sendToWxPayV3(transContext, RequestMethod.GET, RequestProtocol.HTTPS + DomainDetectionUtil.getDomain(), WxApiType.BRAND_PROFIT_SHARING_ORDERS.toString().concat("/").concat(transactionId).concat("/amounts"), null, null);
//        if(dataMap==null){
//            return false;
//        }
//        String unsplitAmount = CastUtil.castString(dataMap.get("unsplit_amount"));
//        // 订单剩余待分金额
//        dataEntry.setChildValue("unsplitAmount", unsplitAmount);
//        // 微信订单号
//        dataEntry.setChildValue("transactionId", transactionId);
//        HyTransUtils.setTransBusSRspSuccessResult(transContext);
//        return true;
//    }
//
//    /**
//     * 查询订单最大分账比例
//     *
//     * @return
//     * @throws Exception
//     */
//    public static boolean profitSharingMerchantRatioQuery(HyTransContext transContext){
//        HyDataEntry dataEntry = transContext.getMess().getDataEntry();
////        Map<String, Object> dataMap = sendToWxPayV3(transContext, RequestMethod.GET, RequestProtocol.HTTPS + DomainDetectionUtil.getDomain(), WxApiType.BRAND_PROFIT_SHARING_CONFIGS.toString().concat("/").concat(Configure.subMchID), null, null);
//        Map<String, Object> dataMap = sendToWxPayV3New(transContext, RequestMethod.GET, RequestProtocol.HTTPS + DomainDetectionUtil.getDomain(), WxApiType.BRAND_PROFIT_SHARING_CONFIGS.toString().concat("/").concat(Configure.subMchID), null, null);
//        if(dataMap==null){
//            return false;
//        }
//        String maxRatio = CastUtil.castString(dataMap.get("max_ratio"));
//        // 最大分账比例
//        dataEntry.setChildValue("maxRatio", maxRatio);
//        HyTransUtils.setTransBusSRspSuccessResult(transContext);
//        return true;
//    }
//
//    /**
//     * 分账回退
//     *
//     * @return
//     * @throws Exception
//     */
//    public static boolean profitSharingReturn(HyTransContext transContext, String body){
//        HyDataEntry dataEntry = transContext.getMess().getDataEntry();
//        Map<String, Object> dataMap = sendToWxPayV3(transContext, RequestMethod.POST, RequestProtocol.HTTPS + DomainDetectionUtil.getDomain(), WxApiType.BRAND_PROFIT_SHARING_RETURN_ORDERS.toString(), body, null);
//        if(dataMap==null){
//            return false;
//        }
//        String orderId = CastUtil.castString(dataMap.get("order_id"));
//        String outOrderNo = CastUtil.castString(dataMap.get("out_order_no"));
//        String outReturnNo = CastUtil.castString(dataMap.get("out_return_no"));
//        String returnMchId = CastUtil.castString(dataMap.get("return_mchid"));
//        String amount = CastUtil.castString(dataMap.get("amount"));
//        String returnNo = CastUtil.castString(dataMap.get("return_no"));
//        String result = CastUtil.castString(dataMap.get("result"));
//        String failReason = CastUtil.castString(dataMap.get("fail_reason"));
//        String finishTime = CastUtil.castString(dataMap.get("finish_time"));
//
//        // 微信分账单号
//        dataEntry.setChildValue("orderId", orderId);
//        // 商户分账单号
//        dataEntry.setChildValue("outOrderNo", outOrderNo);
//        // 商户回退单号
//        dataEntry.setChildValue("outReturnNo", outReturnNo);
//        // 回退商户号
//        dataEntry.setChildValue("returnMchId", returnMchId);
//        // 回退金额
//        dataEntry.setChildValue("amount", amount);
//        // 微信回退单号
//        dataEntry.setChildValue("returnNo", returnNo);
//        // 回退结果
//        dataEntry.setChildValue("result", result);
//        // 失败原因
//        dataEntry.setChildValue("failReason", failReason);
//        // 完成时间
//        dataEntry.setChildValue("finishTime", finishTime);
//        HyTransUtils.setTransBusSRspSuccessResult(transContext);
//        return true;
//    }
//
//    /**
//     * 回退结果查询
//     *
//     * @return
//     * @throws Exception
//     */
//    public static boolean profitSharingReturnQuery(HyTransContext transContext, Map<String, String> params){
//        HyDataEntry dataEntry = transContext.getMess().getDataEntry();
//        Map<String, Object> dataMap = sendToWxPayV3(transContext, RequestMethod.GET, RequestProtocol.HTTPS + DomainDetectionUtil.getDomain(), WxApiType.BRAND_PROFIT_SHARING_RETURN_ORDERS.toString(), null, params);
//        if(dataMap==null){
//            return false;
//        }
//        String orderId = CastUtil.castString(dataMap.get("order_id"));
//        String outOrderNo = CastUtil.castString(dataMap.get("out_order_no"));
//        String outReturnNo = CastUtil.castString(dataMap.get("out_return_no"));
//        String returnMchId = CastUtil.castString(dataMap.get("return_mchid"));
//        String amount = CastUtil.castString(dataMap.get("amount"));
//        String returnNo = CastUtil.castString(dataMap.get("return_no"));
//        String result = CastUtil.castString(dataMap.get("result"));
//        String failReason = CastUtil.castString(dataMap.get("fail_reason"));
//        String finishTime = CastUtil.castString(dataMap.get("finish_time"));
//
//        // 微信分账单号
//        dataEntry.setChildValue("orderId", orderId);
//        // 商户分账单号
//        dataEntry.setChildValue("outOrderNo", outOrderNo);
//        // 商户回退单号
//        dataEntry.setChildValue("outReturnNo", outReturnNo);
//        // 回退商户号
//        dataEntry.setChildValue("returnMchId", returnMchId);
//        // 回退金额
//        dataEntry.setChildValue("amount", amount);
//        // 微信回退单号
//        dataEntry.setChildValue("returnNo", returnNo);
//        // 回退结果
//        dataEntry.setChildValue("result", result);
//        // 失败原因
//        dataEntry.setChildValue("failReason", failReason);
//        // 完成时间
//        dataEntry.setChildValue("finishTime", finishTime);
//        HyTransUtils.setTransBusSRspSuccessResult(transContext);
//        return true;
//    }
//
//    /**
//     * 获取平台证书v3
//     *
//     * @return
//     * @throws Exception
//     */
//    public static boolean platformCertQuery(HyTransContext transContext){
//        HyDataEntry dataEntry = transContext.getMess().getDataEntry();
//        Logger logger = transContext.getLogger();
////       String resJson = wxPayV3(transContext, RequestMethod.GET, RequestProtocol.HTTPS + DomainDetectionUtil.getDomain(), WxApiType.GET_CERTIFICATES.toString(), null, null, false);
//        String resJson = HttpRequestUtil.getReq(RequestProtocol.HTTPS + DomainDetectionUtil.getDomain() + WxApiType.GET_CERTIFICATES.toString(), null, logger, false);
//        if(StringUtil.isEmpty(resJson)){
//            return false;
//        }
//
//        JSONObject jsonObject = JSONUtil.parseObj(resJson);
//        JSONArray dataArray = jsonObject.getJSONArray("data");
//        // 默认认为只有一个平台证书
//        JSONObject encryptObject = dataArray.getJSONObject(0);
//        JSONObject encryptCertificate = encryptObject.getJSONObject("encrypt_certificate");
//        String associatedData = encryptCertificate.getStr("associated_data");
//        String cipherText = encryptCertificate.getStr("ciphertext");
//        String nonce = encryptCertificate.getStr("nonce");
//        String serialNo = encryptObject.getStr("serial_no");
//        final String platSerialNo = savePlatformCert(associatedData, nonce, cipherText, Configure.getPlatformCertPathV3());
//        logger.info("平台证书序列号: {} serialNo: {}", platSerialNo, serialNo);
//
//        HyTransUtils.setTransBusSRspSuccessResult(transContext);
//        return true;
//    }
//
//
//    /**
//     * 保存平台证书v3
//     *
//     * @return
//     * @throws Exception
//     */
//    private static String savePlatformCert(String associatedData, String nonce, String cipherText, String certPath) {
//        try {
//            AesUtil aesUtil = new AesUtil(Configure.getApiKeyV3().getBytes(StandardCharsets.UTF_8));
//            // 平台证书密文解密
//            // encrypt_certificate 中的  associated_data nonce  ciphertext
//            String publicKey = aesUtil.decryptToString(
//                    associatedData.getBytes(StandardCharsets.UTF_8),
//                    nonce.getBytes(StandardCharsets.UTF_8),
//                    cipherText
//            );
//            // 保存证书
//            FileWriter writer = new FileWriter(certPath);
//            writer.write(publicKey);
//            // 获取平台证书序列号
//            X509Certificate certificate = PayKit.getCertificate(new ByteArrayInputStream(publicKey.getBytes()));
//            return certificate.getSerialNumber().toString(16).toUpperCase();
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return null;
//    }
//
//}
